using System;
using System.Collections;
using System.Data;
using System.Text;
using System.Windows.Forms;
using C1.Win.C1Input;
using C1.Win.C1TrueDBGrid;
using PCSComProcurement.Purchase.BO;
using PCSComProcurement.Purchase.DS;
using PCSComUtils.Common;
using PCSComUtils.Common.BO;
using PCSComUtils.PCSExc;
using PCSUtils.Log;
using PCSUtils.Utils;
using CancelEventArgs = System.ComponentModel.CancelEventArgs;

namespace PCSProcurement.Purchase
{
    /// <summary>
    /// Summary description for POPurchaseOrderApproval.
    /// </summary>
    public partial class POPurchaseOrderApproval : Form
    {
        private const string THIS = "PCSProcurement.Purchase.POPurchaseOrderApproval";
        private const string CHECK_APPROVE = "Approved";
        private const string PO_NO = "PONo";
        private const string OPEN_AMOUNT = "openAmount";
        private const string APPROVED_ID = "ApprovedID";
        private const string AVAILABLE_QUANTITY = "AvailableQty";
        private const string CURRENCY = "Currency";
        private const string TRUE = "True";
        private const string PO_APPROVE_TABLE = "POApprove_Table";
        private const string GRIDSOURCE = "GridSource";
        private const string BUYINGUM = "BuyingUM";
        private const string V_PO_NOT_APPROVE = "V_PO_NOT_APPROVE";
        private const string V_PO_APPROVE = "V_PO_APPROVE";
        private bool blnStateOfCheck;
        private DataSet dstGridData;
        private DataTable dtbGridLayOut;
        private DataTable dtbSource = new DataTable(GRIDSOURCE);

        private string strbtnApprove;
        private string strlblApprovalDate;
        private string strlblApprover;

        public POPurchaseOrderApproval()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void POPurchaseOrderApproval_Load(object sender, EventArgs e)
        {
            const string METHOD_NAME = THIS + ".POPurchaseOrderApproval_Load()";
            try
            {
                //Set authorization for user

                var objSecurity = new Security();
                Name = THIS;
                if (objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0)
                {
                    Close();
                    // You don't have the right to view this item
                    PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW, MessageBoxIcon.Warning);
                    return;
                }
                dtbGridLayOut = FormControlComponents.StoreGridLayout(gridApprove);
                // load form
                dtmApprDate.FormatType = FormatTypeEnum.CustomFormat;
                dtmApprDate.CustomFormat = Constants.DATETIME_FORMAT;
                InitVariable();

                cboStatus.Items.Add(lblApproved.Text);
                cboStatus.Items.Add(lblNotApproved.Text);

                strlblApprovalDate = lblApprDate.Text.Trim();
                strbtnApprove = btnApprove.Text.Trim();
                strlblApprover = lblApprover.Text.Trim();

                txtApprover.ReadOnly = true;
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // Displays the error message if throwed from system.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// CreatDataSet
        /// </summary>
        /// <author>Trada</author>
        /// <date>Wednesday, October 12 2005</date>
        private void CreatDataSet()
        {
            dstGridData = new DataSet();
            dstGridData.Tables.Add(PO_APPROVE_TABLE);
            dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(PO_NO);
            dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(PO_PurchaseOrderDetailTable.LINE_FLD);
            dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(ITM_CategoryTable.TABLE_NAME +
                                                             ITM_CategoryTable.CODE_FLD);
            dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(ITM_ProductTable.CODE_FLD);
            dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(ITM_ProductTable.DESCRIPTION_FLD);
            dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(ITM_ProductTable.REVISION_FLD);
            dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(BUYINGUM);
            dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(PO_PurchaseOrderDetailTable.ORDERQUANTITY_FLD);
            dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(AVAILABLE_QUANTITY);
            dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(CURRENCY);
            dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(PO_PurchaseOrderDetailTable.TOTALAMOUNT_FLD);
            dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(OPEN_AMOUNT);
            dstGridData.Tables[PO_APPROVE_TABLE].Columns.Add(CHECK_APPROVE, typeof(bool));
        }

        private void InitVariable()
        {
            // Load combo box
            var boUtil = new UtilsBO();
            DataSet dstCCN = boUtil.ListCCN();
            cboCCN.DataSource = dstCCN.Tables[MST_CCNTable.TABLE_NAME];
            cboCCN.DisplayMember = MST_CCNTable.CODE_FLD;
            cboCCN.ValueMember = MST_CCNTable.CCNID_FLD;
            FormControlComponents.PutDataIntoC1ComboBox(cboCCN, dstCCN.Tables[MST_CCNTable.TABLE_NAME],
                                                        MST_CCNTable.CODE_FLD, MST_CCNTable.CCNID_FLD,
                                                        MST_CCNTable.TABLE_NAME);
            if (SystemProperty.CCNID != 0)
            {
                cboCCN.SelectedValue = SystemProperty.CCNID;
            }

            // Load combo box displays approving date
            var voMasterBlank = new PO_PurchaseOrderMasterVO();
            voMasterBlank.OrderDate = boUtil.GetDBDate();
            if ((DateTime.MinValue < voMasterBlank.OrderDate) && (voMasterBlank.OrderDate < DateTime.MaxValue))
                dtmApprDate.Value = DateTime.Parse(voMasterBlank.OrderDate.ToString());
            else
                dtmApprDate.Value = DBNull.Value;
            // Load approver
            txtApprover.Text = SystemProperty.EmployeeName;
            if (SystemProperty.EmployeeID != 0)
            {
                txtApprover.Tag = SystemProperty.EmployeeID;
            }

            txtApprover.Enabled = false;
            btnShowDetail.Enabled = false;
        }

        private void btnPONo_Click(object sender, EventArgs e)
        {
            const string METHOD_NAME = THIS + ".btnPONo_Click()";
            try
            {
                var htbCriteria = new Hashtable();
                DataRowView drwResult = null;
                //User has selected CCN
                if (cboStatus.Text.Trim() == string.Empty)
                {
                    PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Warning);
                    cboStatus.Focus();
                    return;
                }

                if (cboCCN.SelectedIndex != -1)
                {
                    htbCriteria.Add(PO_PurchaseOrderMasterTable.CCNID_FLD, cboCCN.SelectedValue);
                }
                    //User has not selected CCN
                else
                {
                    PCSMessageBox.Show(ErrorCode.MESSAGE_RGA_CCN, MessageBoxIcon.Warning);
                    cboCCN.Focus();
                    return;
                }
                drwResult = FormControlComponents.OpenSearchForm(cboStatus.Text.Trim() == lblNotApproved.Text.Trim() ? V_PO_NOT_APPROVE : V_PO_APPROVE, PO_PurchaseOrderMasterTable.CODE_FLD, txtPONo.Text.Trim(), htbCriteria, true);
                if (drwResult != null)
                {
                    if ((txtPONo.Tag != null) && (txtPONo.Tag != DBNull.Value))
                    {
                        if (drwResult[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD].ToString() !=
                            txtPONo.Tag.ToString())
                        {
                            txtPONo.Text = drwResult[PO_PurchaseOrderMasterTable.CODE_FLD].ToString();
                            txtPONo.Tag = drwResult[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD];
                            CreatDataSet();
                            gridApprove.DataSource = dstGridData.Tables[0];
                            FormControlComponents.RestoreGridLayout(gridApprove, dtbGridLayOut);
                        }
                    }
                    txtPONo.Text = drwResult[PO_PurchaseOrderMasterTable.CODE_FLD].ToString();
                    txtPONo.Tag = drwResult[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD];
                }
                else
                {
                    txtPONo.Focus();
                }
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            const string METHOD_NAME = THIS + ".btnSearch_Click()";
            try
            {
                if (Validate_Data())
                {
                    BindDataToGrid();
                }
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        private bool Validate_Data()
        {
            if (FormControlComponents.CheckMandatory(cboCCN))
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID);
                cboCCN.Focus();
                return false;
            }
            if (FormControlComponents.CheckMandatory(cboStatus))
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID);
                cboStatus.Focus();
                return false;
            }
            if (FormControlComponents.CheckMandatory(dtmApprDate))
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID);
                dtmApprDate.Focus();
                return false;
            }
            if (FormControlComponents.CheckMandatory(txtApprover))
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID);
                txtApprover.Focus();
                txtApprover.Select();
                return false;
            }
            return true;
        }

        /// <summary>
        /// ConfigGrid
        /// </summary>
        /// <param name="pblnLock"></param>
        /// <author>Trada</author>
        /// <date>Tuesday, Nov 29 2005</date>
        private void ConfigGrid(bool pblnLock)
        {
            gridApprove.Enabled = true;
            for (int i = 0; i < gridApprove.Splits[0].DisplayColumns.Count; i++)
            {
                gridApprove.Splits[0].DisplayColumns[i].Locked = true;
            }
            gridApprove.Splits[0].DisplayColumns[CHECK_APPROVE].Locked = pblnLock;
            gridApprove.Splits[0].DisplayColumns[PO_PurchaseOrderDetailTable.ORDERQUANTITY_FLD].DataColumn.
                NumberFormat = Constants.DECIMAL_NUMBERFORMAT;
            gridApprove.Splits[0].DisplayColumns[PO_PurchaseOrderDetailTable.ORDERQUANTITY_FLD].Style.
                HorizontalAlignment = AlignHorzEnum.Far;
            gridApprove.Splits[0].DisplayColumns[AVAILABLE_QUANTITY].DataColumn.NumberFormat =
                Constants.DECIMAL_NUMBERFORMAT;
            gridApprove.Splits[0].DisplayColumns[AVAILABLE_QUANTITY].Style.HorizontalAlignment = AlignHorzEnum.Far;
            gridApprove.Splits[0].DisplayColumns[PO_PurchaseOrderDetailTable.TOTALAMOUNT_FLD].DataColumn.
                NumberFormat = Constants.DECIMAL_NUMBERFORMAT;
            gridApprove.Splits[0].DisplayColumns[PO_PurchaseOrderDetailTable.TOTALAMOUNT_FLD].Style.
                HorizontalAlignment = AlignHorzEnum.Far;
            gridApprove.Splits[0].DisplayColumns[OPEN_AMOUNT].DataColumn.NumberFormat =
                Constants.DECIMAL_NUMBERFORMAT;
            gridApprove.Splits[0].DisplayColumns[OPEN_AMOUNT].Style.HorizontalAlignment = AlignHorzEnum.Far;
        }

        public void BindDataToGrid()
        {
            chkSelectAll.Checked = false;
            var boPurchase = new POPurchaseOrderApprovalBO();
            if (cboStatus.Text == lblApproved.Text.Trim())
            {
                dtbSource = txtPONo.Text.Trim() != string.Empty ? boPurchase.ListPODetailByPOMasterID(int.Parse(txtPONo.Tag.ToString()), int.Parse(cboCCN.SelectedValue.ToString()), true).Tables[1] : boPurchase.ListPODetailByPOMasterID(-1, int.Parse(cboCCN.SelectedValue.ToString()), true).Tables[1];
            }
            else
            {
                dtbSource = txtPONo.Text.Trim() != string.Empty ? boPurchase.ListPODetailByPOMasterID(int.Parse(txtPONo.Tag.ToString()), int.Parse(cboCCN.SelectedValue.ToString()), false).Tables[1] : boPurchase.ListPODetailByPOMasterID(-1, int.Parse(cboCCN.SelectedValue.ToString()), false).Tables[1];
            }
            dtbSource.Columns.Add(CHECK_APPROVE, typeof(bool));
            dtbSource.Columns.Add(APPROVED_ID);
            foreach (DataRow drow in dtbSource.Rows)
            {
                drow[CHECK_APPROVE] = false;
                if (txtApprover.Text == string.Empty)
                {
                    PCSMessageBox.Show(ErrorCode.MESSAGE_RGV_PURCHASE_APPROVER, MessageBoxIcon.Error);
                    return;
                }
                drow[APPROVED_ID] = txtApprover.Tag.ToString();
            }
            gridApprove.DataSource = dtbSource;
            FormControlComponents.RestoreGridLayout(gridApprove, dtbGridLayOut);
            gridApprove.Splits[0].DisplayColumns[CHECK_APPROVE].DataColumn.Caption = cboStatus.Text.Trim() == lblApproved.Text.Trim()
                                                                                         ? lblCancelApprove.Text.Trim().Substring(1)
                                                                                         : strbtnApprove.Substring(1);
            ConfigGrid(false);
            btnShowDetail.Enabled = gridApprove.Splits[0].Rows.Count > 0;
        }

        private void btnApprove_Click(object sender, EventArgs e)
        {
            const string METHOD_NAME = THIS + ".btnApprove_Click()";
            try
            {
                //Validate data 
                if (FormControlComponents.CheckMandatory(cboCCN))
                {
                    PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID);
                    cboCCN.Focus();
                    return;
                }

                if (FormControlComponents.CheckMandatory(dtmApprDate))
                {
                    PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID);
                    dtmApprDate.Focus();
                    return;
                }

                if (!ValidateData()) return;
                var strListID = new StringBuilder();
                foreach (DataRow dr in dtbSource.Rows)
                    if (dr[CHECK_APPROVE].ToString().Trim() == "True")
                    {
                        if (strListID.Length > 0) strListID.Append(",");
                        strListID.Append(dr[PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD]);
                    }
                int? iApprovedID = null;
                if (cboStatus.SelectedIndex > 0)
                    iApprovedID = Convert.ToInt32(txtApprover.Tag);
                new POPurchaseOrderApprovalBO().UpdateAllApproved(strListID.ToString(),
                                                                  Convert.ToDateTime(dtmApprDate.Value), iApprovedID);
                BindDataToGrid();
                PCSMessageBox.Show(ErrorCode.MESSAGE_AFTER_SAVE_DATA);
            }
            catch (PCSException ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        public bool ValidateData()
        {
            try
            {
                string METHOD_NAME = THIS + ".ValidateData()";
                if (gridApprove.Splits[0].Rows.Count == 0)
                {
                    throw new PCSException(ErrorCode.MESSAGE_PO_APPROVE_NO_DATA_IN_GRID, METHOD_NAME, null);
                }

                int intCount = 0;
                for (int i = 0; i < gridApprove.Splits[0].Rows.Count; i++)
                {
                    if (gridApprove[i, CHECK_APPROVE].ToString() == TRUE)
                    {
                        intCount++;
                        break;
                    }
                }
                if (intCount == 0)
                {
                    PCSMessageBox.Show(ErrorCode.MESSAGE_RGV_PURCHASE_APPROVER_SELECT_LINE, MessageBoxIcon.Warning);
                    return false;
                }

                for (int i = 0; i < gridApprove.Splits[0].Rows.Count; i++)
                {
                    if (gridApprove[i, CHECK_APPROVE].ToString() == TRUE)
                    {
                        if (DateTime.Parse(((DateTime) dtmApprDate.Value).ToShortDateString()) <
                            (DateTime) gridApprove[i, PO_PurchaseOrderMasterTable.ORDERDATE_FLD]
                            && cboStatus.Text.Trim() == lblNotApproved.Text.Trim())
                        {
                            PCSMessageBox.Show(ErrorCode.MESSAGE_RGV_APPROVE_DATE_MUST_OLDER_THAN_ORDER_DATE,
                                               MessageBoxIcon.Warning);
                            dtmApprDate.Focus();
                            return false;
                        }

                        if (DateTime.Parse(((DateTime) dtmApprDate.Value).ToShortDateString()) <
                            (DateTime) gridApprove[i, PO_PurchaseOrderMasterTable.ORDERDATE_FLD]
                            && cboStatus.Text.Trim() == lblApproved.Text.Trim())
                        {
                            PCSMessageBox.Show(ErrorCode.MESSAGE_RGV_CANCEL_APPROVE_DATE_MUST_OLDER_THAN_ORDER_DATE,
                                               MessageBoxIcon.Warning);
                            dtmApprDate.Focus();
                            return false;
                        }
                    }
                }

                //get all POMaster which was selected to approve
                DataRow[] drowIDs = dtbSource.Select(CHECK_APPROVE + "=1");
                var arlIDs = new ArrayList();
                foreach (DataRow drowData in drowIDs)
                {
                    bool okExisted = false;
                    for (int i = 0; i < arlIDs.Count; i++)
                    {
                        if (int.Parse(arlIDs[i].ToString()) ==
                            (int) drowData[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD])
                        {
                            okExisted = true;
                            break;
                        }
                    }
                    if (!okExisted)
                    {
                        arlIDs.Add((int) drowData[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD]);
                    }
                }

                var boPurchase = new POPurchaseOrderApprovalBO();
                for (int i = 0; i < arlIDs.Count; i++)
                {
                    if (
                        !(boPurchase.CheckLevelApproval(int.Parse(txtApprover.Tag.ToString().Trim()),
                                                        int.Parse(arlIDs[i].ToString()),
                                                        int.Parse(cboCCN.SelectedValue.ToString()))))
                    {
                        PCSMessageBox.Show(ErrorCode.MESSAGE_NO_RIGHT_TO_APPROVE, MessageBoxIcon.Stop);
                    }
                }
                return true;
            }
            catch (PCSException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void CheckOrNochkCheckAll()
        {
            for (int i = 0; i < gridApprove.Splits[0].Rows.Count; i++)
            {
                if (gridApprove[i, CHECK_APPROVE].ToString().Trim() != TRUE)
                {
                    chkSelectAll.Checked = false;
                    return;
                }
            }
            chkSelectAll.Checked = true;
        }

        private void chkSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            const string METHOD_NAME = THIS + ".chkSelectAll_CheckedChanged()";
            try
            {
                if (blnStateOfCheck)
                {
                    if (chkSelectAll.Checked)
                    {
                        foreach (DataRow drow in dtbSource.Rows)
                        {
                            if (drow.RowState != DataRowState.Deleted)
                            {
                                drow[CHECK_APPROVE] = true;
                            }
                        }
                    }
                    else
                    {
                        foreach (DataRow drow in dtbSource.Rows)
                        {
                            if (drow.RowState != DataRowState.Deleted)
                            {
                                drow[CHECK_APPROVE] = false;
                            }
                        }
                    }
                }
            }
            catch (PCSException ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        private void gridApprove_AfterColEdit(object sender, ColEventArgs e)
        {
            if (e.Column.DataColumn.DataField == CHECK_APPROVE)
            {
                CheckOrNochkCheckAll();
            }
        }

        private void OnEnterControl(object sender, EventArgs e)
        {
            const string METHOD_NAME = THIS + ".OnEnterControl()";
            try
            {
                FormControlComponents.OnEnterControl(sender, e);
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // Displays the error message if throwed from system.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        private void OnLeaveControl(object sender, EventArgs e)
        {
            const string METHOD_NAME = THIS + ".OnLeaveControl()";
            try
            {
                FormControlComponents.OnLeaveControl(sender, e);
            }
            catch (PCSException ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        private void txtPONo_KeyDown(object sender, KeyEventArgs e)
        {
            const string METHOD_NAME = THIS + ".txtPONo_KeyDown()";
            if (e.KeyCode == Keys.F4)
            {
                btnPONo_Click(sender, e);
            }
        }

        /// <summary>
        /// btnShowDetail_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <author>Trada</author>
        /// <date>Monday, August 15 2005</date>
        private void btnShowDetail_Click(object sender, EventArgs e)
        {
            const string METHOD_NAME = THIS + ".btnShowDetail_Click()";
            try
            {
                if (gridApprove.Splits[0].Rows.Count > 0)
                {
                    var frmPurchaseOrder = new PurchaseOrder();
                    frmPurchaseOrder.Show();
                    frmPurchaseOrder.LoadMaster(
                        (int) gridApprove[gridApprove.Row, PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD]);
                }
            }
            catch (PCSException ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // displays the error message.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                // log message.
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        private void cboStatus_SelectedValueChanged(object sender, EventArgs e)
        {
            const string METHOD_NAME = ".cboStatus_SelectedValueChanged()";
            if (cboStatus.Text.Trim() == lblApproved.Text.Trim())
            {
                btnApprove.Text = lblCancelApprove.Text;
                lblApprDate.Text = lblCancelDate.Text;
                lblApprover.Text = lblCanceler.Text;
                gridApprove.Splits[0].DisplayColumns[CHECK_APPROVE].DataColumn.Caption =
                    lblCancelApprove.Text.Trim().Substring(1);
            }
            if (cboStatus.Text.Trim() == lblNotApproved.Text.Trim())
            {
                btnApprove.Text = strbtnApprove;
                lblApprDate.Text = strlblApprovalDate;
                lblApprover.Text = strlblApprover;
                gridApprove.Splits[0].DisplayColumns[CHECK_APPROVE].DataColumn.Caption = strbtnApprove.Substring(1);
            }
            try
            {
                if (dtbSource.Columns.Count != 0)
                {
                    dtbSource.Rows.Clear();
                    dtbSource.AcceptChanges();
                    gridApprove.Refresh();
                }
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // Displays the error message if throwed from system.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        private void txtPONo_Validating(object sender, CancelEventArgs e)
        {
            const string METHOD_NAME = THIS + ".txtPONo_Validating()";
            try
            {
                if (!txtPONo.Modified || txtPONo.Text.Trim() == string.Empty) return;

                var htbCriteria = new Hashtable();
                DataRowView drwResult = null;
                //User has selected CCN
                if (cboCCN.SelectedIndex != -1)
                    htbCriteria.Add(PO_PurchaseOrderMasterTable.CCNID_FLD, cboCCN.SelectedValue);
                else
                {
                    PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Warning);
                    cboCCN.Focus();
                    e.Cancel = true;
                    return;
                }
                // edited: 12-04-2006 dungla: fix bug 3702 for NganNT, dot not display search form when found only one record
                if (cboStatus.SelectedIndex == -1)
                {
                    var strParam = new string[2];
                    strParam[0] = lblStatus.Text;
                    strParam[1] = lblPONo.Text;
                    PCSMessageBox.Show(ErrorCode.MESSAGE_SELECT_ONE_BEFORE_SELECT_ONE, MessageBoxIcon.Warning, strParam);
                    e.Cancel = true;
                    return;
                }
                if (cboStatus.Text.Trim() == lblNotApproved.Text.Trim())
                    drwResult = FormControlComponents.OpenSearchForm(V_PO_NOT_APPROVE,
                                                                     PO_PurchaseOrderMasterTable.CODE_FLD,
                                                                     txtPONo.Text.Trim(), htbCriteria, false);
                else
                    drwResult = FormControlComponents.OpenSearchForm(V_PO_APPROVE, PO_PurchaseOrderMasterTable.CODE_FLD,
                                                                     txtPONo.Text.Trim(), htbCriteria, false);
                if (drwResult != null)
                {
                    if ((txtPONo.Tag != null) && (txtPONo.Tag != DBNull.Value))
                    {
                        if (drwResult[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD].ToString() !=
                            txtPONo.Tag.ToString())
                        {
                            txtPONo.Text = drwResult[PO_PurchaseOrderMasterTable.CODE_FLD].ToString();
                            txtPONo.Tag = drwResult[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD];
                            CreatDataSet();
                            gridApprove.DataSource = dstGridData.Tables[0];
                            FormControlComponents.RestoreGridLayout(gridApprove, dtbGridLayOut);
                        }
                    }
                    txtPONo.Text = drwResult[PO_PurchaseOrderMasterTable.CODE_FLD].ToString();
                    txtPONo.Tag = drwResult[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD];
                }
                else
                    e.Cancel = true;
            }
            catch (PCSException ex)
            {
                // Displays the error message if throwed from PCSException.
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                // Displays the error message if throwed from system.
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    // Log error message into log file.
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    // Show message if logger has an error.
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
        }

        #region ChangeStateOfCheck

        private void chkSelectAll_Enter(object sender, EventArgs e)
        {
            blnStateOfCheck = true;
        }

        private void chkSelectAll_Leave(object sender, EventArgs e)
        {
            blnStateOfCheck = false;
        }

        #endregion
    }
}